let { jwt, jwtKey } = require('../server_jwt');
let express = require('express');
let router = express.Router();
let db = require('../db');
let xss = require('xss')  // 导入xss模块为了防止用户的脚本攻击


router.post('/one', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            return res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            return res.send({ msg: "登录超时:", login: false });
        }

        // sendResult这个拿来存储返回到客户端的数据
        let sendResult = {};
        let sql_show_post = 'select username, intor, imgList, postID, createTime from post p join users u where p.uid = u.uid and postID = ?';
        let postID = req.body.postID;

        // 第一个查询请求(返回帖子)
        db.query(sql_show_post, postID, (err, result) => {
            if (err) {
                console.log(err.message);
                return res.status(500).send('Server Error');
            }
            sendResult['post'] = result;
            let sql_show_comment = 'select c.createTime, c.content, u.username from commend c join users u where c.uid = u.uid and postID = ?;';

            // 第二个查询请求(返回帖子的评论)
            db.query(sql_show_comment, postID, (err, result) => {
                if (err) {
                    console.log(err.message);
                    return res.status(500).send('Server Error');
                }
                sendResult['commend'] = result;
                res.status(200).json(sendResult);
            })
        })
    })
});

router.post('/sendCommend', (req, res) => {
    const token = req.headers['authorization'];
    jwt.verify(token, jwtKey, (err, decoded) => {
        if (err) {
            return res.send({ msg: "登录验证失败，请重新登录", login: false });
        } else if (parseInt(+new Date() / 1000) >= decoded.exp) {
            return res.send({ msg: "登录超时:", login: false });
        }

        let content = xss(req.body.content);  // 因为用户可以输入内容所以这里检查一下
        let sql_insert_commend = 'insert into commend(postID, content, uid, createTime) values (?, ?, ?, now())'
        db.query(sql_insert_commend, [req.body.postID, content, decoded.uid], (err) => {
            if (err){
                return console.log('数据库处理的时候出错了:', err.message);
            }
            return res.status(200).send("");
        });
    });
});

module.exports = router
